﻿using System;
using System.Collections.Generic;
using System.Linq;
using Medianamik.Core;
using Medianamik.Core.DAL;
using Medianamik.Core.DAL.Repositories;
using Medianamik.Core.DAL.Services;
using Medianamik.Core.Profile;
using SubSonic;

namespace Medianamik.UI.Web.Membership.Data.Repositories
{
    public class UserProfileRepository<TCollection, TItem> :
        MedianamikRepository<TCollection, TItem>,
        IUserProfileRepository<TItem>
        where TItem : IUserProfile, IRecordBase, new()
        where TCollection : ICollectionWithChildren<TCollection, TItem>, new()
    {
        public UserProfileRepository(ICultureService cultureService,
            IContentStateService contentStateService, INodeMapper nodeMapper) :
            base(cultureService, contentStateService, nodeMapper)
        {
        }

        public virtual PagedCollection<TItem> PagedWithFilters(int pageIndex, int pageSize,
            string groupNames, string keywords, ActiveStatus status)
        {
            return new PagedCollection<TItem>(SPs.MedianamikGetUsersByGroups(groupNames, pageSize,
              pageIndex, String.IsNullOrEmpty(keywords) ? null : String.Concat("%", keywords, "%"),
            status == ActiveStatus.All ? default(bool?) :
            (status == ActiveStatus.Activated ? true : false)).ExecuteTypedList<TItem>(),
                GetUsersByGroupsCount(groupNames, keywords, status));
        }

        public virtual int GetUsersByGroupsCount(string groupNames, string keywords, ActiveStatus status)
        {
            using (var reader = SPs.MedianamikGetUsersByGroupsCount(groupNames,
                                                String.IsNullOrEmpty(keywords)
                                                    ? null
                                                    : String.Concat("%", keywords, "%"),
                                                status == ActiveStatus.All
                                                    ? default(bool?)
                                                    : (status == ActiveStatus.Activated ? true : false)).GetReader())
            {
                if (reader.Read())
                    return reader.GetInt32(0);
            }

            throw new Exception("Problemo");
        }

        
    }
}
